/**
 * Copyright 2008 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package kiff;

import kiff.util.LoaderModule;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
/**
 * Junit4 Unit Runner for Running JUnit Tests with in a Guice environment.
 * @author Adam
 * @version $Id: GuiceUnitRunner.java 62 2008-10-31 04:51:50Z a.ruggles $
 * 
 * Created on Sep 30, 2008 at 12:10:14 PM 
 */
public class GuiceUnitRunner extends BlockJUnit4ClassRunner {
	/**
	 * The Guice Injector.
	 */
	protected Injector injector;

	/**
	 * Constructor.
	 * @param klass The Unit Class.
	 * @throws InitializationError If an initialization error occurs.
	 */
	public GuiceUnitRunner(final Class<?> klass) throws InitializationError {
		super(klass);
	}

	/**
	 * {@inheritDoc}
	 * @see org.junit.internal.runners.JUnit4ClassRunner#createTest()
	 */
	@Override
    protected Object createTest() throws Exception {
		Class<?> klass = getTestClass().getJavaClass();
		if (injector != null) {
			return injector.getInstance(klass);
		}
		Module configurationModule;
		if (klass.isAnnotationPresent(ConfigurationLoader.class)) {
			ConfigurationLoader annotation = klass.getAnnotation(ConfigurationLoader.class);
			configurationModule = new LoaderModule(annotation.settings());
		} else {
			configurationModule = new LoaderModule();
		}
		if (Module.class.isAssignableFrom(klass)) {
			injector = Guice.createInjector(
					configurationModule,
					(Module) klass.newInstance());
		} else {
			injector = Guice.createInjector(
					configurationModule);
			injector.injectMembers(klass);
		}
		return injector.getInstance(klass);
	}

}
